﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Drawing2D;

/// <summary>
/// Summary description for Utils
/// </summary>
public class Utils
{
    public Utils()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    private readonly string[] VietnameseSigns = new string[]
     {
      "aAeEoOuUiIdDyY",
      "áàạảãâấầậẩẫăắằặẳẵ",
      "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",
      "éèẹẻẽêếềệểễ",
      "ÉÈẸẺẼÊẾỀỆỂỄ",
      "óòọỏõôốồộổỗơớờợởỡ",
      "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",
      "úùụủũưứừựửữ",
      "ÚÙỤỦŨƯỨỪỰỬỮ",
      "íìịỉĩ",
      "ÍÌỊỈĨ",
      "đ",
      "Đ",
      "ýỳỵỷỹ",
      "ÝỲỴỶỸ"
     };

    public string RemoveSign4VietnameseString(string str)
    {

        //Tiến hành thay thế , lọc bỏ dấu cho chuỗi
        for (int i = 1; i < VietnameseSigns.Length; i++)
        {
            for (int j = 0; j < VietnameseSigns[i].Length; j++)
                str = str.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
        }
        return str;
    }

    public string replaceUrl(String str)
    {
        str = RemoveSign4VietnameseString(str);
        
        str=str.Replace(" ", "-");
        return str;
    }


    public static string GetTitle(string chuoi)
    {
        string[] VietnameseSigns = new string[]
         {
          "aAeEoOuUiIdDyY",
          "áàạảãâấầậẩẫăắằặẳẵ",
          "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",
          "éèẹẻẽêếềệểễ",
          "ÉÈẸẺẼÊẾỀỆỂỄ",
          "óòọỏõôốồộổỗơớờợởỡ",
          "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",
          "úùụủũưứừựửữ",
          "ÚÙỤỦŨƯỨỪỰỬỮ",
          "íìịỉĩ",
          "ÍÌỊỈĨ",
          "đ",
          "Đ",
          "ýỳỵỷỹ",
          "ÝỲỴỶỸ"
         };
        string str = chuoi.ToLower();
        for (int i = 1; i < VietnameseSigns.Length; i++)
        {
            for (int j = 0; j < VietnameseSigns[i].Length; j++)
                str = str.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
        }
        return str.Replace(" ", "-").Replace("?", "").Replace(".", "").Replace("&", "").Replace("''", "").Replace(",", "").Replace("\"", "").Replace("/", "-").Replace("--", "-");

    }


    public String checkNull(List<WebControl> lstTb)
    {
        foreach (WebControl item in lstTb)
        {
            if (item.GetType().ToString() == "System.Web.UI.WebControls.DropDownList")
            {
                DropDownList drop = (DropDownList)item;
                if (drop.SelectedValue == "0")
                {
                    item.Focus();
                    return "Lỗi không được để trống";
                }
            }
            if (item is System.Web.UI.WebControls.TextBox)
            {
                TextBox text = (TextBox)item;
                if (text.Text == "")
                {
                    item.Focus();
                    item.BackColor = System.Drawing.Color.Yellow;
                    return "Lỗi không được để trống";
                }
                item.BackColor = System.Drawing.Color.White;
            }

        }
        return "";
    }

    public string checkDangNhap(ObjTaiKhoan objTaiKhoan)
    {
        TaiKhoan taiKhoan = new TaiKhoan();
        objTaiKhoan = taiKhoan.logIn(objTaiKhoan);
        if (objTaiKhoan.User_name == "")
        {
            return "/error.aspx?type=" + Constants.LOI_KHONG_DANG_NHAP;
        }
        return "";
    }

   

    public string checkDataType(List<WebControl> lst)
    {
        int number;
        float numbet01;
        foreach (WebControl ctl in lst)
        {
            if (ctl.Attributes["DataType"] == "integer")
            {
                if ((!Int32.TryParse(((ITextControl)ctl).Text, out number)))
                {
                    ctl.Focus();
                    ctl.BackColor = System.Drawing.Color.Yellow;
                    return "Lỗi nhập số liệu";
                }
            }
            if (ctl.Attributes["DataType"] == "email")
            {
                Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
                Match match = regex.Match(((ITextControl)ctl).Text);
                if (match.Success)
                    return "";
                else
                {
                    ctl.Focus();
                    ctl.BackColor = System.Drawing.Color.Yellow;
                    return "Mail không đúng";
                }
            }

            if (ctl.Attributes["DataType"] == "float")
            {
                if ((!float.TryParse(((ITextControl)ctl).Text, out numbet01)))
                {
                    ctl.Focus();
                    ctl.BackColor = System.Drawing.Color.Yellow;
                    return "Lỗi nhập số liệu";
                }
            }
            if (ctl.Attributes["DataType"] == "anh")
            {
                if (ctl is System.Web.UI.WebControls.FileUpload)
                {
                    FileUpload file = (FileUpload)ctl;
                    if (file.FileBytes.Length == 0)
                    {
                        file.BackColor = System.Drawing.Color.Yellow;
                        file.Focus();
                        return "chưa chọn file";
                    }
                    string ext = System.IO.Path.GetExtension(file.FileName).TrimStart(".".ToCharArray()).ToLower();
                    if ((ext != "jpeg") && (ext != "jpg") && (ext != "png") && (ext != "gif") && (ext != "bmp"))
                    {
                        file.Focus();
                        file.BackColor = System.Drawing.Color.Yellow;
                        return "lỗi sai định dạng ảnh";
                    }
                    
                }
            }
            ctl.BackColor = System.Drawing.Color.White;
        }
        return "";
    }

    public string getMD5(string txt)
    {
        string source = txt;
        MD5 md5 = MD5.Create();
        string hash = GetMd5Hash(md5, source);
        return hash;
    }

    static string GetMd5Hash(MD5 md5Hash, string input)
    {

        // Convert the input string to a byte array and compute the hash. 
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes 
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data  
        // and format each one as a hexadecimal string. 
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        // Return the hexadecimal string. 
        return sBuilder.ToString();
    }

    // Verify a hash against a string. 
    static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
    {
        // Hash the input. 
        string hashOfInput = GetMd5Hash(md5Hash, input);

        // Create a StringComparer an compare the hashes.
        StringComparer comparer = StringComparer.OrdinalIgnoreCase;

        if (0 == comparer.Compare(hashOfInput, hash))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public Bitmap resizeAnhNho(FileUpload fileUpload)
    {
        Bitmap anh_goc = new Bitmap(fileUpload.FileContent);
        Bitmap anh_ket_qua = new Bitmap(Constants.WITH, Constants.HEIGHT);
        Graphics g = Graphics.FromImage(anh_ket_qua);
        g.Clear(Color.FromArgb(255, 255, 255));
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;

        int with;
        int height;
        //giu chieu cao
        if (Constants.HEIGHT * anh_goc.Width / anh_goc.Height <= Constants.WITH)
        {
            with=(int)(Constants.HEIGHT * anh_goc.Width / anh_goc.Height);
            g.DrawImage(anh_goc, (Constants.WITH - with) / 2, 0, with, Constants.HEIGHT);
        }
        //giu chieu rong
        else
        {
            height = (int)(Constants.WITH * anh_goc.Height / anh_goc.Width);
            g.DrawImage(anh_goc, 0, (Constants.HEIGHT - height)/ 2, Constants.WITH, height);

        }
        //Graphics.FromImage(bm1).DrawImage(bm, 0, 0, 1004, 1466);
        //Graphics.FromImage(bm1).DrawString("Hồng phước", new Font("Tahoma",12), Brushes.Red, new PointF(0,0));
        //System.Drawing.Image img=System.Drawing.Image.FromFile(MapPath("/images/")+"chonmua.jpg");
        //Rectangle rect = new Rectangle(100, 100, 200, 200);
        //Graphics.FromImage(bm1).DrawImage(img, new PointF(100,100));
        //anh_trung_gian.Save(MapPath("/images/") + photoUpload.FileName);
        return anh_ket_qua;
    }

    public Bitmap resizeAnh(FileUpload fileUpload, int width, int height)
    {
        Bitmap anh_goc = new Bitmap(fileUpload.FileContent);
        Bitmap anh_ket_qua = new Bitmap(width, height);
        Graphics g = Graphics.FromImage(anh_ket_qua);
        //g.Clear(Color.FromArgb(255, 255, 255));
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;

        int width_tg;
        int height_tg;
        //giu chieu cao
        if (height * anh_goc.Width / anh_goc.Height <= width)
        {
            width_tg = (int)(height * anh_goc.Width / anh_goc.Height);
            g.DrawImage(anh_goc, (width - width_tg) / 2, 0, width_tg, height);
        }
        //giu chieu rong
        else
        {
            height_tg = (int)(width * anh_goc.Height / anh_goc.Width);
            g.DrawImage(anh_goc, 0, (height - height_tg) / 2, width, height_tg);

        }
        return anh_ket_qua;
    }


    public Bitmap resizeAnhTo(FileUpload fileUpload)
    {
        Bitmap anh_goc = new Bitmap(fileUpload.FileContent);
       

        int height;
        height = Constants.ANH_TO_WITH * anh_goc.Height / anh_goc.Width;
        Bitmap anh_ket_qua = new Bitmap(Constants.ANH_TO_WITH, height);
        Graphics g = Graphics.FromImage(anh_ket_qua);
        g.Clear(Color.FromArgb(255, 255, 255));
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.DrawImage(anh_goc, 0, 0, Constants.ANH_TO_WITH, height);
        //Graphics.FromImage(bm1).DrawImage(bm, 0, 0, 1004, 1466);
        //Graphics.FromImage(bm1).DrawString("Hồng phước", new Font("Tahoma",12), Brushes.Red, new PointF(0,0));
        //System.Drawing.Image img=System.Drawing.Image.FromFile(MapPath("/images/")+"chonmua.jpg");
        //Rectangle rect = new Rectangle(100, 100, 200, 200);
        //Graphics.FromImage(bm1).DrawImage(img, new PointF(100,100));
        //anh_trung_gian.Save(MapPath("/images/") + photoUpload.FileName);
        return anh_ket_qua;
    }

    public static string FormartPrice(string price)
    {
        if (price.Length < 2)
        {
            return price;
        }
        else
        {
            return String.Format("{0:0,0}", int.Parse(price)); 
        }
    }
}